package com.unlcn.ils.kas.service.order.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.collect.Maps;
import com.unlcn.ils.kas.dao.model.order.*;
import com.unlcn.ils.kas.service.map.BaiDuMap.util.BaiDuMapGeocodeUtil;
import com.unlcn.ils.kas.service.map.BaiDuMap.util.BaiDuMapRouteUtil;
import com.unlcn.ils.kas.service.order.*;
import com.unlcn.ils.kas.service.util.ErpUrl;
import com.unlcn.ils.kas.service.util.HttpClientUtil;
import com.unlcn.ils.kas.service.util.enums.order.*;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 江铃控股订单调度 service 实现
 * 
 * @author 罗必量
 */
@Service
public class HoldingOrderServiceImpl implements HoldingOrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HoldingOrderServiceImpl.class);

    /**
     * 订单在途日志 service
     */
    @Autowired
    private OrderOtdLogService orderOtdLogService;

    /**
     * 订单在途日志明细 service
     */
    @Autowired
    private OrderOtdLogDetailService orderOtdLogDetailService;

    /**
     * 订单在途跟踪 service
     */
    @Autowired
    private OrderOtdService orderOtdService;

    /**
     * 订单在途跟踪明细 service
     */
    @Autowired
    private OrderOtdDetailService orderOtdDetailService;

    /**
     * 客户 service
     */
    @Autowired
    private CustomerService customerService;

    /**
     * 拉取订单异常 service
     */
    @Autowired
    private OrderOtdExceptionService orderOtdExceptionService;

    /**
     * 执行日志 service
     */
    @Autowired
    private PushOrderLogService pushOrderLogService;

    /**
     * erp 接口地址 model
     */
    @Autowired
    private ErpUrl erpUrl;

    @Value("${get.erp.getErpKgTime}")
    private String loadTime;

    @Override
    public void pushOrder1() {
        String format = "yyyy-MM-dd HH:mm:ss";
        DateTime dt = new DateTime();
        Integer year = dt.getYear();
        Integer month = dt.getMonthOfYear();
        int day = dt.getDayOfMonth();
        DateTime todayDateTime = new DateTime(year, month, day, 0, 0, 0);
        DateTime yesterdayDateTime = new DateTime(year, month, day, 13, 30, 0);
        yesterdayDateTime = yesterdayDateTime.minusDays(1);
        String endTime = todayDateTime.toString(format);
        String startTime = yesterdayDateTime.toString(format);

        getOrder(startTime, endTime);
    }

    @Override
    public void pushOrder2() {
        String format = "yyyy-MM-dd HH:mm:ss";
        DateTime dt = new DateTime();
        Integer year = dt.getYear();
        Integer month = dt.getMonthOfYear();
        int day = dt.getDayOfMonth();
        DateTime startDateTime = new DateTime(year, month, day, 0, 0, 0);
        DateTime endDateTime = new DateTime(year, month, day, 13, 30, 0);
        String startTime = startDateTime.toString(format);
        String endTime = endDateTime.toString(format);

        getOrder(startTime, endTime);
    }

    /**
     * 获取订单详情、订单在途信息 定时任务
     */
    @Override
    public void getOrder(String startTime, String endTime) {
        LOGGER.info("拉取控股订单====================");
        PushOrderLog pushOrderLog = new PushOrderLog();
        Integer executNum = 0; // 已经执行的数量
        Integer insertNum = 0; // 插入数
        Integer updateNum = 0; // 更新数
        Integer abnormalNum = 0; // 异常数

        // 获取线程名称
        String pushThreadName = Thread.currentThread().getName();
        pushOrderLog.setPushThreadName(pushThreadName);
        // 拉取控股订单（记录拉取日志）
        pushOrderLog.setType(PushOrderLogTypeEnum.KG.getCode());
        // 开始执行时间
        pushOrderLog.setStartExecutTime(new Date());

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<NameValuePair> orderParams = new ArrayList<>();
        orderParams.add(new BasicNameValuePair("icustomerid", CustomNoEnum.KG.getValue()));
        orderParams.add(new BasicNameValuePair("startTime", startTime));
        orderParams.add(new BasicNameValuePair("endTime", endTime));
        Date callStartTime = new Date();
        String getOrderNoResult = HttpClientUtil.get(erpUrl.getGetErpKgOrderNo(), orderParams, 600000000);
        Date callEndTime = new Date();
        if (StringUtils.isEmpty(getOrderNoResult))
            return;

        // 将订单号转换成map集合
        List<Map> orderMapNoList = getMap(getOrderNoResult);
        LOGGER.info(simpleDateFormat.format(new Date()) + "拉取了" + orderMapNoList.size() + "条订单(控股)");

        // 拉取数量
        pushOrderLog.setDataNum(orderMapNoList.size());

        if (orderMapNoList.size() == 0) {
            // 完成时间
            pushOrderLog.setFinshExecutTime(new Date());
            // 记录执行日志
            pushOrderLogService.insert(pushOrderLog);
            return;
        }

        // 遍历转换成的mao，一一存储进数据库
        for (Map map : orderMapNoList) {
            String vcdn = map.get("vcdn").toString();

            try {
                // 请求获取订单详情
                List<NameValuePair> orderDetailParams = new ArrayList<>();
                orderDetailParams.add(new BasicNameValuePair("vcdn", vcdn));
                String getOrderDetailResult = HttpClientUtil.get(erpUrl.getGetErpOrderDetail(), orderDetailParams,
                        600000000);
                LOGGER.info("(" + vcdn + ")获取订单详情接口返回信息: ", getOrderDetailResult);
                if (StringUtils.isEmpty(getOrderDetailResult))
                    continue;

                // 格式化返回的订单详情信息
                JSONObject json = JSONObject.parseObject(getOrderDetailResult);
                Object obj = json.get("data");
                LOGGER.info("(" + vcdn + ")" + "详情: ", obj);
                if (obj == null)
                    continue;
                OrderOtdLog orderOtdLog = analysisOrder((Map) obj);
                orderOtdLog.setCallUrl(erpUrl.getGetErpKgOrderNo());
                orderOtdLog.setCallStartTime(callStartTime);
                orderOtdLog.setCallEndTime(callEndTime);

                List<NameValuePair> onWayParams = new ArrayList<>();
                onWayParams.add(new BasicNameValuePair("vcdn", orderOtdLog.getSysOrderNo()));
                String onWayResult = HttpClientUtil.get(erpUrl.getGetErpOnway(), onWayParams, 600000000);

                List<OrderOtdLogDetail> orderOtdLogDetailList = new ArrayList<>();
                if (!StringUtils.isEmpty(onWayResult)) {
                    // 将在途信息转换成map集合
                    List<Map> onWayList = getMap(onWayResult);

                    if (!CollectionUtils.isEmpty(onWayList)) {
                        for (Map onWayMap : onWayList) {
                            OrderOtdLogDetail orderOtdLogDetail = analysisOnWayInfo(onWayMap);
                            orderOtdLogDetailList.add(orderOtdLogDetail);
                        }
                    }
                }

                // 保存订单详细信息、在途信息
                String executWay = saveOrderInfo(orderOtdLog, orderOtdLogDetailList);

                if (executWay.equals("insert")) {
                    insertNum++;
                    pushOrderLog.setInsertNum(insertNum);
                } else if (executWay.equals("update")) {
                    updateNum++;
                    pushOrderLog.setUpdateNum(updateNum);
                }
                executNum++;
                pushOrderLog.setExecutNum(executNum);
                List<PushOrderLog> pushOrderLogList = pushOrderLogService
                        .selectNowDay(PushOrderLogTypeEnum.KG.getCode(), pushThreadName);
                if (CollectionUtils.isEmpty(pushOrderLogList)) {
                    // 完成时间
                    pushOrderLog.setFinshExecutTime(new Date());
                    // 记录执行日志
                    pushOrderLogService.insert(pushOrderLog);
                } else {
                    pushOrderLog.setId(pushOrderLogList.get(0).getId());
                    // 完成时间
                    pushOrderLog.setFinshExecutTime(new Date());
                    // 记录执行日志
                    pushOrderLogService.updateById(pushOrderLog);
                }
            } catch (Exception e) {
                LOGGER.error("拉取订单" + vcdn + "发生异常", e);

                // 保存异常信息
                OrderOtdException orderOtdException = new OrderOtdException();
                orderOtdException.setSysOrderCode(vcdn);
                orderOtdException.setExceptionMsg(JSON.toJSONString(e));
                orderOtdException.setFlag(OrderOtdExceptionEnum.UNTREATED.getCode());
                orderOtdException.setGmtCreate(new Date());
                saveOrderException(orderOtdException);

                abnormalNum++;
                executNum++;
                pushOrderLog.setAbnormalNum(abnormalNum);
                pushOrderLog.setExecutNum(executNum);

                List<PushOrderLog> pushOrderLogList = pushOrderLogService
                        .selectNowDay(PushOrderLogTypeEnum.KG.getCode(), pushThreadName);
                if (CollectionUtils.isEmpty(pushOrderLogList)) {
                    // 完成时间
                    pushOrderLog.setFinshExecutTime(new Date());
                    // 记录执行日志
                    pushOrderLogService.insert(pushOrderLog);
                } else {
                    pushOrderLog.setId(pushOrderLogList.get(0).getId());
                    // 完成时间
                    pushOrderLog.setFinshExecutTime(new Date());
                    // 记录执行日志
                    pushOrderLogService.updateById(pushOrderLog);
                }

                continue;
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public String saveOrderInfo(OrderOtdLog orderOtdLog, List<OrderOtdLogDetail> orderOtdLogDetailList) {

        // 执行方式
        String executWay = null;

        // 保存在途跟踪日志表
        orderOtdLog.setGmtCreate(new Date());
        orderOtdLogService.insert(orderOtdLog);
        // 保存在途跟踪日志明细信息
        for (int i = 0; orderOtdLogDetailList.size() > i; i++) {
            orderOtdLogDetailList.get(i).setHeadId(orderOtdLog.getId());
        }
        if (!CollectionUtils.isEmpty(orderOtdLogDetailList)) {
            orderOtdLogDetailService.batchInsert(orderOtdLogDetailList);
        }

        // 校验订单是否已经存在 kas 订单跟踪表
        EntityWrapper<OrderOtd> ew = new EntityWrapper<>();
        ew.eq("sys_order_no", orderOtdLog.getSysOrderNo());
        List<OrderOtd> orderOtdList = orderOtdService.selectList(ew);

        // 转换跟踪订单
        OrderOtd orderOtd = transformation(orderOtdLog, orderOtdList);

        // 存在则更新，否则插入
        if (!CollectionUtils.isEmpty(orderOtdList)) {

            // 如果订单在kas里已经存在 运抵时间||回单时间，则不更新
            if (orderOtdList.get(0).getShiptoTime() == null && orderOtdList.get(0).getReturnOrderTime() == null) {

                // 保存在途跟踪明细信息
                LOGGER.info(orderOtdLogDetailList.size() + "条在途信息");
                saveDetail(orderOtd, orderOtdLogDetailList);
            }

            // 更新在途跟踪表
            orderOtd.setId(orderOtdList.get(0).getId());
            orderOtd.setGmtCreate(orderOtdList.get(0).getGmtCreate());
            orderOtd.setGmtModified(new Date());

            orderOtdService.updateById(orderOtd);
            LOGGER.info("(" + orderOtd.getSysOrderNo() + ")成功更新订单");

            executWay = "update";
        } else {
            // 保存在途跟踪表
            orderOtd.setGmtCreate(new Date());
            orderOtdService.insert(orderOtd);
            LOGGER.info("成功插入订单", orderOtd.getSysOrderNo());

            // 保存在途跟踪明细信息
            LOGGER.info(orderOtdLogDetailList.size() + "条在途信息");
            saveDetail(orderOtd, orderOtdLogDetailList);

            executWay = "insert";
        }

        return executWay;
    }

    @Override
    public void saveDetail(OrderOtd orderOtd, List<OrderOtdLogDetail> orderOtdLogDetailList) {
        LOGGER.info(orderOtdLogDetailList.size() + "条在途信息");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 保存在途跟踪明细信息
        for (OrderOtdLogDetail orderOtdLogDetail : orderOtdLogDetailList) {

            // 不保存重复在途信息
            Wrapper<OrderOtdDetail> detailEntity = new EntityWrapper();
            detailEntity.eq("tid", orderOtdLogDetail.gettId());
            List<OrderOtdDetail> orderOtdDetails = orderOtdDetailService.selectList(detailEntity);
            if (CollectionUtils.isEmpty(orderOtdDetails)) {
                detailEntity.eq("track_time", simpleDateFormat.format(orderOtdLogDetail.getTrackTime()));
                detailEntity.eq("sys_order_no", orderOtdLogDetail.getSysOrderNo());
                orderOtdDetails = orderOtdDetailService.selectList(detailEntity);
            }
            if (!CollectionUtils.isEmpty(orderOtdDetails))
                continue;

            OrderOtdDetail orderOtdDetail = new OrderOtdDetail();
            BeanUtils.copyProperties(orderOtdLogDetail, orderOtdDetail);

            orderOtdDetail.setHeadId(orderOtd.getId());

            // 计算运输距离
            Number distance = computationalDistance(orderOtd, orderOtdDetail);
            orderOtdDetail.setDistance(distance.floatValue());

            // 查看存不存在比手动维护的时间要晚，并且距离要远的数据
            Wrapper<OrderOtdDetail> wrapper = new EntityWrapper<>();
            wrapper.eq("sys_order_no", orderOtdDetail.getSysOrderNo());
            wrapper.eq("ismanual", OrderDetailIsmanualEnum.YES.getCode());
            wrapper.lt("track_time", simpleDateFormat.format(orderOtdDetail.getTrackTime()));
            wrapper.lt("distance", orderOtdDetail.getDistance());
            wrapper.eq("isdelete", OrderDetailDeleteFlagEnum.NORMAL.getCode());
            if (!CollectionUtils.isEmpty(orderOtdDetailService.selectList(wrapper)))
                continue;

            orderOtdDetailService.insert(orderOtdDetail);
        }
    }

    /**
     * 计算运输距离
     * 
     * @param orderOtd
     * @param orderOtdDetail
     * @return
     */
    @Override
    public Number computationalDistance(OrderOtd orderOtd, OrderOtdDetail orderOtdDetail) {

        Number distance = 0.00;

        if (orderOtdDetail == null)
            return distance;

        if (orderOtdDetail.getLatitude() == null || orderOtdDetail.getLongitude() == null) {
            // 计算运输距离
            String startAddress = orderOtdDetail.getProvince() + orderOtdDetail.getCity() + orderOtdDetail.getArea()
                    + orderOtdDetail.getAddress();
            String endAddress = orderOtd.getdProvince() + orderOtd.getdCity() + orderOtd.getdAddress();
            distance = getDistance(startAddress, endAddress);
        } else {
            Map<String, Double> mapOrgrin = Maps.newHashMap();
            mapOrgrin.put("lat", Double.valueOf(orderOtdDetail.getLatitude().toString()));
            mapOrgrin.put("lng", Double.valueOf(orderOtdDetail.getLongitude().toString()));

            String cords = mapOrgrin.get("lng") + "," + mapOrgrin.get("lat");
            List<Map<String, Double>> lists = BaiDuMapGeocodeUtil.geoConv(cords, 1, 5);
            if (!CollectionUtils.isEmpty(lists)) {
                Map<String, Double> mapGeo = lists.get(0);

                String destination = null;

                // 根据详细地址获取距离
                destination = orderOtd.getdAddress();
                Map<String, Double> mapDestinations = BaiDuMapGeocodeUtil.addressToGPS(destination);
                distance = BaiDuMapRouteUtil.getDistance(mapGeo, mapDestinations) / 1000;

                // 如果详细地址无法获取距离，则根据省市区加详细地址
                if (distance == null || 0 >= distance.doubleValue()) {
                    destination = (orderOtd.getdProvince()) == null ? ""
                            : orderOtd.getdProvince() + (orderOtd.getdCity()) == null ? ""
                                    : orderOtd.getdCity() + (orderOtd.getdAddress()) == null ? ""
                                            : orderOtd.getdAddress();
                    mapDestinations = BaiDuMapGeocodeUtil.addressToGPS(destination);
                    distance = BaiDuMapRouteUtil.getDistance(mapGeo, mapDestinations) / 1000;
                }
            }
        }

        return distance;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void saveOrderException(OrderOtdException orderOtdException) {
        orderOtdExceptionService.insert(orderOtdException);
    }

    /**
     * 转换跟踪订单
     * 
     * @param orderOtdLog
     * @param orderOtdList
     * @return
     */
    @Override
    public OrderOtd transformation(OrderOtdLog orderOtdLog, List<OrderOtd> orderOtdList) {

        OrderOtd orderOtd = new OrderOtd();

        BeanUtils.copyProperties(orderOtdLog, orderOtd);

        // 查询客户编号
        EntityWrapper<Customer> customerEntity = new EntityWrapper<>();
        customerEntity.eq("name", orderOtd.getCustomerName());
        List<Customer> customerList = customerService.selectList(customerEntity);
        if (!CollectionUtils.isEmpty(customerList)) {
            orderOtd.setCustomerNo(customerList.get(0).getCode());
        }

        // 计算起运地到目的地的距离
        String startAddress = orderOtd.getoProvince() + orderOtd.getoCity() + orderOtd.getoAddress();
        String endAddress = orderOtd.getdProvince() + orderOtd.getdCity() + orderOtd.getdAddress();
        orderOtd.setDistance(getDistance(startAddress, endAddress).floatValue());

        // 数据源
        orderOtd.setWay(OrderWayEnum.WAY_SYS_INTF.getCode());

        // 如果手动不为空 就拿最后一条维护最新在途位置
        if (!CollectionUtils.isEmpty(orderOtdList) && orderOtdList.get(0).getManualShiptoTime() != null) {
            // 获取最新在途
            OrderOtdDetail orderOtdDetail = orderOtdDetailService.selectNewestInfo(orderOtd.getSysOrderNo());
            if (orderOtdDetail != null) {
                String newestPosition = (StringUtils.isEmpty(orderOtdDetail.getProvince()) ? ""
                        : orderOtdDetail.getProvince() + "-")
                        + (StringUtils.isEmpty(orderOtdDetail.getCity()) ? "" : orderOtdDetail.getCity() + "-")
                        + (StringUtils.isEmpty(orderOtdDetail.getArea()) ? "" : orderOtdDetail.getArea() + "-")
                        + (StringUtils.isEmpty(orderOtdDetail.getAddress()) ? "" : orderOtdDetail.getAddress());
                orderOtd.setNewestPosition(newestPosition);
                orderOtd.setNewestTime(orderOtdDetail.getTrackTime());
            }
        }

        // 判断挂起状态
        if (orderOtd.getBsuspend() != null) {
            // 0正常订单；1挂起订单
            if (orderOtd.getBsuspend() == 0) {
                // 如果 kas 手动司机联系方式为空，则更新 tms 同步信息
                if (CollectionUtils.isEmpty(orderOtdList)
                        || StringUtils.isEmpty(orderOtdList.get(0).getManualDriverPhone())) {
                    orderOtd.setDriverPhone(orderOtdLog.getDriverPhone());
                } else {
                    orderOtd.setDriverPhone(orderOtdList.get(0).getManualDriverPhone());
                }
                // 如果 kas 手动运抵时间为空，则更新 tms 同步信息
                if (CollectionUtils.isEmpty(orderOtdList)
                        || StringUtils.isEmpty(orderOtdList.get(0).getManualShiptoTime())) {
                    orderOtd.setShiptoTime(orderOtdLog.getShiptoTime());
                } else {
                    orderOtd.setShiptoTime(orderOtdList.get(0).getManualShiptoTime());
                }
            } else if (orderOtd.getBsuspend() == 1) {
                orderOtd.setManualDriverPhone(null);
                orderOtd.setManualShiptoTime(null);
            }
        }

        // 判断订单状态
        if (orderOtd.getLeaveTime() == null) {
            orderOtd.setOrderStatus("未离昌");
        }
        if (orderOtd.getLeaveTime() != null) {
            orderOtd.setOrderStatus("在途");
        }
        if (orderOtd.getShiptoTime() != null) {
            orderOtd.setOrderStatus("交付");
        }

        return orderOtd;
    }

    /**
     * 获取两地距离
     * 
     * @param startAddress
     * @param endAddress
     * @return
     */
    @Override
    public Double getDistance(String startAddress, String endAddress) {

        if (StringUtils.isEmpty(startAddress) || StringUtils.isEmpty(endAddress))
            return 0.0;

        startAddress = startAddress.replaceAll("null", "");
        endAddress = endAddress.replaceAll("null", "");

        Double distance = BaiDuMapRouteUtil.getDistance(startAddress, endAddress);
        if (distance == null) {
            return 0.0;
        }
        distance = distance / 1000;

        return distance;
    }

    /**
     * 将ResponseEntity结果转换成map集合
     * 
     * @param result
     * @return
     */
    @Override
    public List<Map> getMap(String result) {

        List<Map> dataMapList = new ArrayList<Map>();

        JSONObject json = JSONObject.parseObject(result);

        if (json == null || json.get("data") == null)
            return dataMapList;

        JSONArray jsonArray = JSONArray.parseArray(json.get("data").toString());

        if (jsonArray == null || jsonArray.size() == 0)
            return dataMapList;

        // 遍历订单JSON串，一一转换成map
        for (Object obj : jsonArray) {
            Map map = (Map) obj;
            dataMapList.add(map);
        }

        return dataMapList;
    }

    /**
     * 格式化在途信息
     * 
     * @param map
     * @return
     */
    @Override
    public OrderOtdLogDetail analysisOnWayInfo(Map map) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        OrderOtdLogDetail orderOtdLogDetail = new OrderOtdLogDetail();
        if (map == null)
            return orderOtdLogDetail;

        try {
            // 明细 id
            if (!StringUtils.isEmpty(map.get("tid"))) {
                orderOtdLogDetail.settId(map.get("tid").toString());
            }
            // 在途时间
            if (!StringUtils.isEmpty(map.get("dtlocation"))) {
                orderOtdLogDetail.setTrackTime(simpleDateFormat.parse(map.get("dtlocation").toString()));
            }
            // 所在省
            if (!StringUtils.isEmpty(map.get("vcprovince"))) {
                orderOtdLogDetail.setProvince(map.get("vcprovince").toString());
            }
            // 所在市
            if (!StringUtils.isEmpty(map.get("vccity"))) {
                orderOtdLogDetail.setCity(map.get("vccity").toString());
            }
            // 所在区/县
            if (!StringUtils.isEmpty(map.get("vcarea"))) {
                orderOtdLogDetail.setArea(map.get("vcarea").toString());
            }
            // 详细地址
            if (!StringUtils.isEmpty(map.get("vclocation"))) {
                orderOtdLogDetail.setAddress(map.get("vclocation").toString());
            }
            // 经度
            if (!StringUtils.isEmpty(map.get("vclongitude"))) {
                orderOtdLogDetail.setLongitude(new BigDecimal(map.get("vclongitude").toString()));
            }
            // 纬度
            if (!StringUtils.isEmpty(map.get("vclatitude"))) {
                orderOtdLogDetail.setLatitude(new BigDecimal(map.get("vclatitude").toString()));
            }
            // 系统订单号
            if (!StringUtils.isEmpty(map.get("vcdn"))) {
                orderOtdLogDetail.setSysOrderNo(map.get("vcdn").toString());
            }
        } catch (Exception e) {
            LOGGER.error("OrderScheduled.analysisOnWayInfo ERROR: ", e);
        }

        return orderOtdLogDetail;
    }

    /**
     * 格式化订单
     * 
     * @param map
     * @return
     */
    @Override
    public OrderOtdLog analysisOrder(Map map) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        OrderOtdLog orderOtdLog = new OrderOtdLog();
        if (map == null)
            return orderOtdLog;

        try {
            // 离昌时间
            if (!StringUtils.isEmpty(map.get("dtonway"))) {
                orderOtdLog.setLeaveTime(simpleDateFormat.parse(map.get("dtonway").toString()));
            }
            // 安排运力时间
            if (!StringUtils.isEmpty(map.get("dtassign"))) {
                orderOtdLog.setArrangeCapacityTime(simpleDateFormat.parse(map.get("dtassign").toString()));
            }
            // 入铁路库时间
            if (!StringUtils.isEmpty(map.get("dt2rail"))) {
                orderOtdLog.setEnterRailwayTime(simpleDateFormat.parse(map.get("dt2rail").toString()));
            }
            // 入中转库时间
            if (!StringUtils.isEmpty(map.get("dtcache"))) {
                orderOtdLog.setInboundTime(simpleDateFormat.parse(map.get("dtcache").toString()));
            }
            // 订单创建时间
            if (!StringUtils.isEmpty(map.get("dtcreate"))) {
                orderOtdLog.setOrderCreateTime(simpleDateFormat.parse(map.get("dtcreate").toString()));
            }
            // 运抵时间
            if (!StringUtils.isEmpty(map.get("dtdelivery"))) {
                orderOtdLog.setShiptoTime(simpleDateFormat.parse(map.get("dtdelivery").toString()));
            }
            // 最新在途时间
            if (!StringUtils.isEmpty(map.get("dtlocation"))) {
                orderOtdLog.setNewestTime(simpleDateFormat.parse(map.get("dtlocation").toString()));
            }
            // 订单日期
            if (!StringUtils.isEmpty(map.get("dtorder"))) {
                orderOtdLog.setOrderDate(simpleDateFormat.parse(map.get("dtorder").toString()));
            }
            // 出中联库时间
            if (!StringUtils.isEmpty(map.get("dtout_3pl"))) {
                orderOtdLog.setOutboundTime(simpleDateFormat.parse(map.get("dtout_3pl").toString()));
            }
            // 提车时间
            if (!StringUtils.isEmpty(map.get("dtout_factory"))) {
                orderOtdLog.setPickTime(simpleDateFormat.parse(map.get("dtout_factory").toString()));
            }
            // 装车时间
            if (!StringUtils.isEmpty(map.get("dtload"))) {
                orderOtdLog.setLoadTime(simpleDateFormat.parse(map.get("dtload").toString()));
            }
            // 客户编号
            if (!StringUtils.isEmpty(map.get("icustomerid"))) {
                orderOtdLog.setCustomerNo(map.get("icustomerid").toString());
            }
            // 收车地址
            if (!StringUtils.isEmpty(map.get("vcaddress_dest"))) {
                orderOtdLog.setdAddress(map.get("vcaddress_dest").toString());
            }
            // 发车地址
            if (!StringUtils.isEmpty(map.get("vcaddress_origin"))) {
                orderOtdLog.setoAddress(map.get("vcaddress_origin").toString());
            }
            // 收车城市
            if (!StringUtils.isEmpty(map.get("vccity_dest"))) {
                orderOtdLog.setdCity(map.get("vccity_dest").toString());
            }
            // 发车城市
            if (!StringUtils.isEmpty(map.get("vccity_origin"))) {
                orderOtdLog.setoCity(map.get("vccity_origin").toString());
            }
            // 客户名称
            if (!StringUtils.isEmpty(map.get("vccustomer"))) {
                orderOtdLog.setCustomerName(map.get("vccustomer").toString());
            }
            // 经销商名称
            if (!StringUtils.isEmpty(map.get("vcdealername"))) {
                orderOtdLog.setDealerName(map.get("vcdealername").toString());
            }
            // 经销商编号
            if (!StringUtils.isEmpty(map.get("vcdealerno"))) {
                orderOtdLog.setDealerNo(map.get("vcdealerno").toString());
            }
            // 客户订单号
            if (!StringUtils.isEmpty(map.get("vcdmsorderno"))) {
                orderOtdLog.setCustomerOrderNo(map.get("vcdmsorderno").toString());
            }
            // 系统订单号
            if (!StringUtils.isEmpty(map.get("vcdn"))) {
                orderOtdLog.setSysOrderNo(map.get("vcdn").toString());
            }
            // 系统订单号
            if (!StringUtils.isEmpty(map.get("vcdn"))) {
                orderOtdLog.setSysOrderNo(map.get("vcdn").toString());
            }
            // 司机联系方式
            if (!StringUtils.isEmpty(map.get("vcdriver"))) {
                orderOtdLog.setDriverPhone(map.get("vcdriver").toString());
            }
            // 车牌号
            if (!StringUtils.isEmpty(map.get("vclicense"))) {
                orderOtdLog.setLicensePlate(map.get("vclicense").toString());
            }
            // 最新在途位置
            if (!StringUtils.isEmpty(map.get("vclocation"))) {
                orderOtdLog.setNewestPosition(map.get("vclocation").toString());
            }
            // 收车省
            if (!StringUtils.isEmpty(map.get("vcprovince_dest"))) {
                orderOtdLog.setdProvince(map.get("vcprovince_dest").toString());
            }
            // 发车省
            if (!StringUtils.isEmpty(map.get("vcprovince_origin"))) {
                orderOtdLog.setoProvince(map.get("vcprovince_origin").toString());
            }
            // 车型名称
            if (!StringUtils.isEmpty(map.get("vcstylename"))) {
                orderOtdLog.setStyleName(map.get("vcstylename").toString());
            }
            // 车型编码
            if (!StringUtils.isEmpty(map.get("vcstyleno"))) {
                orderOtdLog.setStyleCode(map.get("vcstyleno").toString());
            }
            // 运输方式
            if (!StringUtils.isEmpty(map.get("vctransmode"))) {
                orderOtdLog.setTransportType(map.get("vctransmode").toString());
            }
            // 发运类型
            if (!StringUtils.isEmpty(map.get("vctype"))) {
                orderOtdLog.setShipmentType(map.get("vctype").toString());
            }
            // 车架号
            if (!StringUtils.isEmpty(map.get("vcvin"))) {
                orderOtdLog.setVin(map.get("vcvin").toString());
            }
            // 打单时间
            if (!StringUtils.isEmpty(map.get("dtprint"))) {
                orderOtdLog.setPrintOrderTime(simpleDateFormat.parse(map.get("dtprint").toString()));
            }
            // 回单时间
            if (!StringUtils.isEmpty(map.get("dtreturn"))) {
                orderOtdLog.setReturnOrderTime(simpleDateFormat.parse(map.get("dtreturn").toString()));
            }
            // 承运车队名称
            if (!StringUtils.isEmpty(map.get("vcsupplier"))) {
                orderOtdLog.setSupplier(map.get("vcsupplier").toString());
            }
            // 挂起状态，0正常1挂起
            if (!StringUtils.isEmpty(map.get("bsuspend"))) {
                orderOtdLog.setBsuspend(Integer.valueOf(map.get("bsuspend").toString()));
            }
        } catch (Exception e) {
            LOGGER.error("OrderScheduled.analysisOrder ERROR: ", e);
        }

        return orderOtdLog;
    }
}
